package cn.dubito.miaosha.rabbitmq.receiver;

import cn.dubito.miaosha.domain.SeckillOrder;
import cn.dubito.miaosha.domain.SeckillUser;
import cn.dubito.miaosha.rabbitmq.MqConfig;
import cn.dubito.miaosha.rabbitmq.message.SeckillMessage;
import cn.dubito.miaosha.redis.RedisService;
import cn.dubito.miaosha.service.GoodsService;
import cn.dubito.miaosha.service.OrderService;
import cn.dubito.miaosha.service.SeckillService;
import cn.dubito.miaosha.vo.GoodsVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author liliang
 * @description:
 * @date 2018/4/10.
 */
@Service
public class MqReceiver {

    @Autowired
    private RedisService redisService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private SeckillService seckillService;

    private static Logger logger = LoggerFactory.getLogger(MqReceiver.class);

    @RabbitListener(queues = MqConfig.SECKILL_QUEUE)
    public void receiveSeckill(String message) {
        logger.info("receive seckill message : {}", message);
        SeckillMessage seckillMessage = redisService.stringToBean(message, SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodsId();
        SeckillUser user = seckillMessage.getUser();

        // 判断库存
        GoodsVO goods = goodsService.getGoodsDetailByGoodsId(goodsId);
        int stockCount = goods.getStockCount();
        if (stockCount > 0) {
            // 是否重复秒杀
            SeckillOrder seckillOrder = orderService.getSeckillOrderByUserIdAndGoodsId(user.getId(), goodsId);
            if (seckillOrder == null) {
                // 减库存,下订单,写入秒杀订单
                seckillService.seckill(user, goods);
            }
        }
    }

//
//    @RabbitListener(queues = MqConfig.QUEUE)
//    public void receive(String message) {
//        logger.info("receive message : {}", message);
//    }
//
//    @RabbitListener(queues = MqConfig.TOPIC_QUEUE1)
//    public void receiveTopic1(String message) {
//        logger.info("receive topic queue1 message : {}", message);
//    }
//
//    @RabbitListener(queues = MqConfig.TOPIC_QUEUE2)
//    public void receiveTopic2(String message) {
//        logger.info("receive topic queue2 message : {}", message);
//    }
//
//    @RabbitListener(queues = MqConfig.HEAD_QUEUE)
//    public void receiveHead(byte[] message) {
//        logger.info("receive header queue message : {}", new String(message));
//    }
}
